import {Injectable} from '@angular/core';
import {Headers, Http} from '@angular/http';
import {HttpClient} from '@angular/common/http';
import {AppConfig} from '../config';
import {DatePipe} from '@angular/common';
import {LossElectricity} from '../entity/loss-electricity.model';
import {InterceptorService} from './interceptor/interceptor-service';
import {FarmRow} from '../module/monitor/keytarget/keytarget.component';
import {Rpower} from '../entity/rpower.model';

@Injectable()
export class LossElectricityService {
  private fomat: string = 'yyyy-MM-dd';
  private readonly param = 'reportPower';

  private get url(): string {
    return `${AppConfig.APP_RESTFUL}/${this.param}`;
  }

  private headers = new Headers({
    'Content-Type': 'application/json'
  });

  constructor(private http: InterceptorService, private datePipe: DatePipe, private http2: HttpClient) {
  }

  create(rpower: Rpower): Promise<boolean> {
    return this.http.post(this.url, JSON.stringify(rpower))
      .toPromise()
      .then(res => {
        try {
          let result = res;
          switch (result.code) {
            case '200':
              return true;
            case '-1':
              throw new Error(result.message);
          }
        }
        catch (error) {
          this.handleError(error);
        }
      })
      .catch(this.handleError);
  }

  update(rpower: Rpower): Promise<Rpower> {
    const url = `${this.url}`;
    return this.http.put(url, JSON.stringify(rpower))
      .toPromise()
      .then(() => rpower)
      .catch(this.handleError);
  }

  //获取风场的损失电量和实发电量
  // getFarmPowerLossElectricity(farmId: number, dateType: number, date: Date): Promise<LossElectricityListData> {
  //   let dateFomat: string = '';
  //   dateFomat = this.datePipe.transform(date, this.fomat);
  //   //'http://192.168.15.150:8585/webapi/v1/powerLosses/getPowerLossRankByAllFarms'
  //   return this.http.post(this.url, JSON.stringify({ 'farmId': farmId, 'dateType': dateType, 'date': dateFomat}), { headers: this.headers })
  //     .toPromise()
  //     .then(response => {
  //       let resault = response;
  //       try {
  //         switch (resault.code) {
  //           case '200':
  //             return resault.data as LossElectricityListData;
  //           case '-1':
  //             throw new Error(resault.message);
  //         }
  //       }
  //       catch (error) {
  //         throw error;
  //       }
  //     })
  //     .catch(this.handleError);
  // }
  getFarmPowerByTime(startTime: string, endTime: string, dateType: number): Promise<Rpower[]> {
    const obj = {
      startTime: startTime,
      endTime: endTime,
      dateType: dateType
    };
    return this.http.post(`${this.url}/getPower`, JSON.stringify(obj), {headers: this.headers})
      .toPromise()
      .then(response => {
        return response.data as Rpower[];
      })
      .catch(this.handleError);
  }

  getFaultlossByTime(startTime: string, endTime: string): Promise<Rpower[]> {
    const obj = {
      startTime: startTime,
      endTime: endTime
    };
    return this.http.post(`${this.url}/getFaultloss`, JSON.stringify(obj), {headers: this.headers})
      .toPromise()
      .then(response => {
        return response.data as Rpower[];
      })
      .catch(this.handleError);
  }

  getPredictionPowerByTime(startTime: string): Promise<Rpower[]> {
    const obj = {
      startTime: startTime,
    };
    return this.http.post(`${this.url}/getPredictionPower`, JSON.stringify(obj), {headers: this.headers})
      .toPromise()
      .then(response => {
        return response.data as Rpower[];
      })
      .catch(this.handleError);
  }

  getPowerType(): Promise<PowerType[]> {
    return this.http.get(`${this.url}/getPowerType`)
      .toPromise()
      .then(response => {
        return response.data as PowerType[];
      })
      .catch(this.handleError);
  }

  //获取风场的损失电量和实发电量
  getFarmPowerLossElectricity(farmId: number, year: number, month: number): Promise<LossElectricityListData> {
    // const url = `http://192.168.15.3:8989/webapi/v1/rPowers/getLPAnalysis/farmId/${farmId}/year/${year}/month/${month}`;
    const url = `${this.url}/getLPAnalysis/farmId/${farmId}/year/${year}/month/${month}`;
    return this.http.get(url)
      .toPromise()
      .then(response => {
        return response.data as LossElectricityListData
      })
      .catch(this.handleError);
  }

  getFarmRPowerByTime(time: Date) {
    const dateFomat = this.datePipe.transform(time, this.fomat);
    const url = `${this.url}/time/${dateFomat}`;
    return this.http.get(url)
      .toPromise()
      .then(response => {
        return response.data as FarmRow[];
      })
      .catch(this.handleError);
  }

  importBattery(file) {
    let formData = new FormData();
    formData.append('file', file[0], file[0].name);
    const url = `${this.url}/importBattery`;
    return this.http2.post(url, formData)
      .toPromise()
      .then(res => res)
      .catch(this.handleError);
  }

  importAvgwindspeed(file) {
    let formData = new FormData();
    formData.append('file', file[0], file[0].name);
    const url = `${this.url}/importAvgwindspeed`;
    return this.http2.post(url, formData)
      .toPromise()
      .then(res => res)
      .catch(this.handleError);
  }

  importOtherBattery(file) {
    let formData = new FormData();
    formData.append('file', file[0], file[0].name);
    const url = `${this.url}/importOtherBattery`;
    return this.http2.post(url, formData)
      .toPromise()
      .then(res => res)
      .catch(this.handleError);
  }

  importDayPower(file) {
    let formData = new FormData();
    formData.append('file', file[0], file[0].name);
    const url = `${this.url}/importReportFile`;
    return this.http2.post(url, formData)
      .toPromise()
      .then(res => res)
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    return Promise.reject(error.message || error);
  }
}


interface LossElectricityList {
  realPowers: LossElectricity[],
  lossPowers: LossElectricity[]
}

interface LossElectricityListData {
  farm: LossElectricityList,
  turbine: LossElectricityList
}

export interface PowerType {
  caltype: number;
  categoryDesc: string;
  categoryId: number;
  categoryKey: string;
  categoryName: string;
  categorytag: number;
  dbname: string;
  iscalculate: boolean;
  isindb: boolean;
  priority: number;
}


// WEBPACK FOOTER //
// ./src/app/service/loss-electricity.service.ts
